﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using SBACN.WebSite.Cache;
using SBACN.WebSite.Common;
using SBACN.WebSite.Models;

namespace SBACN.WebSite.Code
{
	public abstract class BasePage : System.Web.UI.Page
	{
		/// <summary>
		/// 当前页面的业务代码
		/// </summary>
		public string SystemCode
		{
			get
			{
				if (ViewState["SystemCode"] == null)
				{
					return string.Empty;
				}
				return ViewState["SystemCode"].ToString();
			}
			set
			{
				ViewState["SystemCode"] = value;
			}
		}

		/// <summary>
		/// 根据Request中的st参数，初始化页面的业务代码
		/// </summary>
		/// <param name="e"></param>
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			if (!string.IsNullOrWhiteSpace(Request["st"]))
				this.SystemCode = Request["st"].Trim();
			ClientScript.RegisterClientScriptBlock(this.GetType(), "Baidu", "<div style='display:none;'><script type=\"text/javascript\">var _bdhmProtocol = ((\"https:\" == document.location.protocol) ? \" https://\" : \" http://\");document.write(unescape(\"%3Cscript src='\" + _bdhmProtocol + \"hm.baidu.com/h.js%3F441ee6efc9495ecbc72d29d3c55ffc73' type='text/javascript'%3E%3C/script%3E\"));</script></div>", false);
		}

		/// <summary>
		/// 网站根路径
		/// </summary>
		public static string RootPath
		{
			get
			{
				return HostSetting.RootPath;
			}
		}

		/// <summary>
		/// 管理目录的根路径
		/// </summary>
		public static string AdminPath
		{
			get
			{
				return HostSetting.AdminPath;
			}
		}

		/// <summary>
		/// 管理员默认页
		/// </summary>
		public static string AdminDefaultPage
		{
			get
			{
				return HostSetting.AdminDefaultPage;
			}
		}

		/// <summary>
		/// 管理员登录页
		/// </summary>
		public static string AdminLoginPage
		{
			get
			{
				return HostSetting.AdminLoginPage;
			}
		}

		/// <summary>
		/// 上传文件夹路径
		/// </summary>
		public static string UploadRootPath
		{
			get
			{
				return HostSetting.UploadRootPath;
			}
		}

		/// <summary>
		/// 允许上传的文件大小
		/// </summary>
		public static int MaxUploadSize
		{
			get
			{
				return HostSetting.MaxUploadSize;
			}
		}

		/// <summary>
		/// 允许上传的文件类型
		/// </summary>
		public static string UploadFileTypes
		{
			get
			{
				return HostSetting.UploadFileTypes;
			}
		}

		/// <summary>
		/// 普通用户默认页
		/// </summary>
		public static string MemberDefaultPage
		{
			get
			{
				return HostSetting.MemberDefaultPage;
			}
		}

		/// <summary>
		/// 普通用户登录页
		/// </summary>
		public static string MemberLoginPage
		{
			get
			{
				return HostSetting.MemberLoginPage;
			}
		}

		/// <summary>
		/// 获取客户端IP地址
		/// </summary>
		/// <returns></returns>
		public static string GetRequestIP(HttpRequest request)
		{
			if (!string.IsNullOrEmpty(request.ServerVariables["HTTP_VIA"])) // using proxy
			{
				//return request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  // Return real client IP.
				return request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null ? request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString() : "127.0.0.1";// Return real client IP.
			}
			else// not using proxy or can't get the Client IP
			{
				return request.ServerVariables["REMOTE_ADDR"] != null ? request.ServerVariables["REMOTE_ADDR"].ToString() : "127.0.0.1"; //While it can't get the Client IP, it will return proxy IP.

				//return request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
			}
		}

		/// <summary>
		/// 关闭当前窗口并终止当前请求
		/// </summary>
		/// <param name="refreshOpener">是否刷新父页面</param>
		public static void CloseWindow(bool refreshOpener)
		{
			string clientJs = "<script type=\"text/javascript\" language=\"javascript\">";
			if (refreshOpener)
			{
				clientJs += "if(window.opener && window.opener.Refresh) window.opener.Refresh();";
			}
			clientJs += "window.close();</script>";
			HttpContext.Current.Response.Write(clientJs);
			HttpContext.Current.Response.End();
		}

		/// <summary>
		/// 跳转到指定窗口，并提示用户
		/// </summary>
		/// <param name="url"></param>
		/// <param name="msg"></param>
		public static void RedirectWithMessage(string url, string msg)
		{
			string retURL = HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.RawUrl);
			url += (url.IndexOf("?") > 0 ? "&returl=" : "?returl=") + retURL;
			string clientJs = "<script type=\"text/javascript\" language=\"javascript\">";
			//clientJs += "window.alert(\"" + msg + "\");window.location = \"" + url + "\";";
			clientJs += "if (window.confirm(\"" + msg + "\")) {window.location = \"" + url + "\";} else { if(navigator.userAgent.toUpperCase().indexOf(\"MSIE\")==-1){if(window.history.length > 1){window.history.go(-1);}else{window.close();}} else {if(window.history.length > 0){window.history.go(-1);}else{window.close();}} }";
			clientJs += "</script>";

			HttpContext.Current.Response.Write(clientJs);
			HttpContext.Current.Response.End();
		}

		public static string GetFileExt(string FullPath)
		{
			if (FullPath != string.Empty) 
				return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower().Trim();
			else
				return string.Empty;
		}

		public static void CreateFolder(string FolderPath)
		{
			if (!System.IO.Directory.Exists(FolderPath))
				System.IO.Directory.CreateDirectory(FolderPath);
		}
		
		/// <summary>
		/// 根据字典Code获取名称
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		public static string TranslateToName(string code)
		{
			TB_SystemMap map =  SystemMapCache.Instance[code];
			if(map != null)
			{
				return map.Name;
			}
			else
			{
				return string.Empty;
			}
		}
		/// <summary>
		/// 根据字典Code获取中文显示值
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		public static string TranslateToCText(string code)
		{
			TB_SystemMap map = SystemMapCache.Instance[code];
			if (map != null)
			{
				return map.CText;
			}
			else
			{
				return string.Empty;
			}
		}
		/// <summary>
		/// 根据字典Code获取英文显示值
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		public static string TranslateToEText(string code)
		{
			TB_SystemMap map = SystemMapCache.Instance[code];
			if (map != null)
			{
				return map.EText;
			}
			else
			{
				return string.Empty;
			}
		}

		/// <summary>
		/// 上传文件
		/// </summary>
		/// <param name="code">文件业务代码</param>
		/// <param name="fileName">原始文件名</param>
		/// <param name="inputStream">文件流</param>
		/// <returns>存储文件的URL</returns>
		public static string UploadFile(string code, string fileName, byte[] inputStream)
		{
			if (inputStream.Length == 0 || inputStream.Length > (MaxUploadSize * 1024 * 1024))
			{
				throw new Exception("上传的文件大小不符合系统设置!");
			}

			string extension = GetFileExt(fileName);
			if (("," + UploadFileTypes + ",").ToLower().IndexOf(("," + extension + ",").ToLower()) < 1)
			{
				throw new Exception("上传的文件类型不符合系统设置!");
			}

			string uploadpath = UploadRootPath + "day_" + DateTime.Now.ToString("yyyyMMdd") + (string.IsNullOrWhiteSpace(code) ? "/" : "/" + code.ToLower() + "/");

			Random random = new Random();
			string filename = uploadpath + DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(99999).ToString("#00000") + "." + extension;

			BasePage.CreateFolder(HttpContext.Current.Server.MapPath(uploadpath));

			using(System.IO.FileStream fs = new System.IO.FileStream(HttpContext.Current.Server.MapPath(filename), System.IO.FileMode.Create, System.IO.FileAccess.Write))
			{
				fs.Write(inputStream, 0, inputStream.Length);
				fs.Flush();
				fs.Close();
			}

			return filename;
		}

		/// <summary>
		/// url添加不重复的request
		/// </summary>
		/// <param name="url">url</param>
		/// <param name="key">request的key</param>
		/// <param name="value">request的value</param>
		/// <returns></returns>
		public static string UrlAppendQueryString(string url, string key, string value, bool replace)
		{
			if (string.IsNullOrWhiteSpace(url) || url == "#")
			{
				return "#";
			}
			else
			{
				Regex TicketRegex = new Regex(@"([?&])(" + key + "=[^&]*&?)");
				if(replace)
				{
					while (url.Contains("?" + key + "=") || url.Contains("&" + key + "="))
					{
						url = TicketRegex.Replace(url, new MatchEvaluator(delegate(Match match)
						{
							return match.Groups[1].Value;
						}));
					}

					if (url.Contains("?"))
					{
						url += "&" + key + "=" + value;
					}
					else
					{
						url += "?" + key + "=" + value;
					}
				}
				else
				{
					if (!url.Contains("?" + key + "=") && !url.Contains("&" + key + "="))
					{
						url += url.Contains("?") ? "&" + key + "=" + value : "?" + key + "=" + value;
					}
				}
			}
			return url;
		}

		/// <summary>
		/// 生成指定长度的密码
		/// </summary>
		/// <param name="length">密码长度</param>
		/// <returns></returns>
		public static string GeneratePassword(int length)
		{
			string passwordString = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*(),.[]?{}";
			char[] character = passwordString.ToCharArray();
			string retValue = string.Empty;
			Random rnd = new Random();
			for (int i = 0; i < length; i++)
			{
				retValue += character[rnd.Next(character.Length)];
			}
			return retValue;
		}
	}
}